# Flask框架导入
from flask import render_template, redirect, url_for, request, flash

# 蓝图和装饰器导入
from . import userinfo_bp
from ..utils import member_login_required, get_current_member, get_accessible_menus
from inc.models import AdminDepartment

@userinfo_bp.route('/')
@member_login_required
def view_profile():
    """查看用户资料"""

    member = get_current_member()
    return render_template('member/userinfo/profile.html', member=member)

@userinfo_bp.route('/edit', methods=['GET', 'POST'])
@member_login_required
def edit_profile():
    """编辑用户资料"""
    member = get_current_member()
    departments = AdminDepartment.query.order_by(AdminDepartment.name).all()

    if request.method == 'POST':
        # 处理密码修改逻辑
        new_password = request.form.get('new_password')
        confirm_password = request.form.get('confirm_password')
        current_password = request.form.get('current_password')

        if new_password or confirm_password or current_password:
            # 验证密码修改
            if not current_password:
                flash('修改密码需要输入当前密码', 'danger')
                return render_template('member/userinfo/edit_profile.html',
                                    member=member, departments=departments)

            if not member.check_password(current_password):
                flash('当前密码不正确', 'danger')
                return render_template('member/userinfo/edit_profile.html',
                                    member=member, departments=departments)

            if new_password != confirm_password:
                flash('新密码与确认密码不匹配', 'danger')
                return render_template('member/userinfo/edit_profile.html',
                                    member=member, departments=departments)

            if new_password:
                member.set_password(new_password)
                flash('密码修改成功', 'success')

        # 更新基本信息
        member.mobile = request.form.get('mobile', member.mobile)
        member.email = request.form.get('email', member.email)

        db.session.commit()
        flash('个人信息更新成功', 'success')
        return redirect(url_for('member.userinfo.view_profile'))

    return render_template('member/userinfo/edit_profile.html',
                         member=member, departments=departments)